package com.dtjd.playcoinmonkey.activities;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAdSdk;
import com.bytedance.sdk.openadsdk.TTRewardVideoAd;
import com.dtjd.playcoinmonkey.ChildClick;
import com.dtjd.playcoinmonkey.MyApplication;
import com.dtjd.playcoinmonkey.R;
import com.dtjd.playcoinmonkey.bean.HttpParaBean;
import com.dtjd.playcoinmonkey.databinding.ActivityPostBinding;
import com.dtjd.playcoinmonkey.utils.Network;
import com.dtjd.playcoinmonkey.utils.Tools;
import com.github.dhaval2404.imagepicker.ImagePicker;

import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class PostActivity extends AppCompatActivity {

    private ActivityPostBinding binding;
    private int originWidth=0;
    private File post_file;
    private ProgressDialog dialog;
    private ActivityResultLauncher<Intent> launcher;
    private void lookAd(ChildClick click) {
        if (dialog==null){
            dialog = new ProgressDialog(this);
            dialog.setTitle(getString(R.string.tips));
            dialog.setCanceledOnTouchOutside(false);
            dialog.setMessage(getString(R.string.loading));
        }
        dialog.show();
        TTAdNative mTTAdNative = TTAdSdk.getAdManager().createAdNative(this);
        AdSlot adSlot = new AdSlot.Builder().setCodeId("946899756").setMediaExtra(MyApplication.sp.getString("token","")).setSupportDeepLink(true).setRewardName("Ticket").setRewardAmount(1).setUserID("user0").setExpressViewAcceptedSize(500,500).setOrientation(TTAdConstant.VERTICAL).build();
        mTTAdNative.loadRewardVideoAd(adSlot, new TTAdNative.RewardVideoAdListener() {
            @Override
            public void onError(int code, String message) {
                dialog.dismiss();
            }
            @Override
            public void onRewardVideoCached(TTRewardVideoAd ttRewardVideoAd) {
                dialog.dismiss();
                ttRewardVideoAd.showRewardVideoAd(PostActivity.this);
            }
            @Override
            public void onRewardVideoAdLoad(TTRewardVideoAd ad) {
                ad.setRewardAdInteractionListener(new TTRewardVideoAd.RewardAdInteractionListener() {
                    @Override
                    public void onAdShow() { }
                    @Override
                    public void onAdVideoBarClick() { }
                    @Override
                    public void onAdClose() { click.click(null,0);}
                    @Override
                    public void onVideoComplete() { }
                    @Override
                    public void onVideoError() { }
                    @Override
                    public void onRewardVerify(boolean rewardVerify, int rewardAmount, String rewardName, int i1, String s1) {
                        if (rewardVerify) Tools.toast( getString(R.string.congratulation));
                    }
                    @Override
                    public void onSkippedVideo() {
                    }
                });
            }
            @Override
            public void onRewardVideoCached() {
            }
        });

    }
    private void post() {
        if (binding.writeEditTitle.getText().toString().equals("")){
            Tools.toast( getResources().getString(R.string.title_cant_blank));
            return;
        }
        if (binding.writeEdit.getText().toString().equals("")){
            Tools.toast( getResources().getString(R.string.content_cant_blank));
            return;
        }
        boolean has;
        if (post_file!=null){
            has= post_file.exists();
        }else {
            has=false;
        }
        List<HttpParaBean> list=new ArrayList<>();
        list.add(new HttpParaBean("token","token"));
        list.add(new HttpParaBean("title",binding.writeEditTitle.getText().toString()));
        list.add(new HttpParaBean("content",binding.writeEdit.getText().toString()));
        list.add(new HttpParaBean("postArea","1"));
        if (has){
            Network.upload("wbhMain/addPost", post_file,list, new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    e.printStackTrace();
                }
                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) {
                    runOnUiThread(() -> {
                        try {
                            Tools.toast( new JSONObject(response.body().string()).getString("datalist"));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        finish();
                    });
                }
            });
        }else {
            Network.post(list,"wbhMain/addPost", new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    e.printStackTrace();
                }
                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) {
                    runOnUiThread(() -> {
                        try {
                            Tools.toast( new JSONObject(response.body().string()).getString("datalist"));
                        } catch (Exception e){
                            e.printStackTrace();
                        }
                        finish();
                    });
                }
            });
        }
    }
    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding=ActivityPostBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        originWidth= Tools.dip2px(this,binding.postImg.getLayoutParams().width);
        binding.postImg.setOnClickListener(view -> {
            ViewGroup.LayoutParams para = binding.postImg.getLayoutParams();
            if (para.width!=-1){
                ImagePicker.with(this).cropSquare().compress(1024).maxResultSize(1080, 1080).createIntent(intent -> {
                    launcher.launch(intent);
                    return null;
                });
            }else{
                AlertDialog.Builder dialog=new AlertDialog.Builder(this);
                dialog.setMessage(getResources().getString(R.string.deleteConfirm)).setPositiveButton(getResources().getString(R.string.delete), (dialogInterface, i) -> {
                    para.height=Tools.px2dip(this,originWidth);
                    para.width=Tools.px2dip(this,originWidth);
                    binding.postImg.setLayoutParams(para);
                    binding.postImg.setImageResource(R.drawable.add_post);
                }).setNegativeButton(getResources().getString(R.string.cancel),null).show();
            }
        });
        binding.postBack.setOnClickListener(view -> finish());
        binding.postPost.setOnClickListener(view -> {
            List<HttpParaBean> para=new ArrayList<>();
            para.add(new HttpParaBean("token","token"));
            if (MyApplication.needTicket) {
                Network.post(para, "wbhMain/getTickets", new Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        e.printStackTrace();
                    }
                    @SuppressLint("StringFormatMatches")
                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) {
                        runOnUiThread(() -> {
                            try {
                                JSONObject jo = new JSONObject(response.body().string());
                                if (jo.getInt("code") == 1) {
                                    if (jo.getJSONArray("datalist").getJSONObject(0).getInt("ticket") > 0) {
                                        Tools.showDialog(PostActivity.this,
                                                String.format(getResources().getString(R.string.restTicket), jo.getJSONArray("datalist").getJSONObject(0).getInt("ticket")),
                                                String.format(getResources().getString(R.string.dialog_content_post), "1"),
                                                getResources().getString(R.string.cancel),
                                                (o, dialog) -> dialog.dismiss(), getResources().getString(R.string.confirm), (o, dialog) -> {
                                                    dialog.dismiss();
                                                    post();
                                                });
                                    } else {
                                        Tools.showDialog(PostActivity.this,
                                                String.format(getResources().getString(R.string.restTicket), jo.getJSONArray("datalist").getJSONObject(0).getInt("ticket")),
                                                getResources().getString(R.string.ticketNotEnough),
                                                getResources().getString(R.string.watching),
                                                (o, dialog) -> {
                                                    dialog.dismiss();
                                                /*
                                                看完后给三张扣除1张，
                                                 */
                                                    lookAd((v, position) -> post());
                                                }, getResources().getString(R.string.cancel), (o, dialog) -> dialog.dismiss());
                                    }
                                } else {
                                    Tools.toast( getResources().getString(R.string.getTicketFaild));
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        });
                    }
                });
            }else {
                post();
            }
        });

        launcher=registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            if (result.getResultCode() == Activity.RESULT_OK) {
                post_file = new File(result.getData().getData().getPath());
                ViewGroup.LayoutParams para = binding.postImg.getLayoutParams();
                if (para.width==-1){
                    para.height=Tools.px2dip(this,originWidth);
                    para.width=Tools.px2dip(this,originWidth);
                }else {
                    para.height=-1;
                    para.width=-1;
                }
                binding.postImg.setLayoutParams(para);
                binding.postImg.setImageURI(result.getData().getData());
            } else if (result.getResultCode() == ImagePicker.RESULT_ERROR) {
                Tools.toast(ImagePicker.getError(result.getData()));
            }
        });
    }
}